package com.neolix.watch.bluetooth;

import android.app.Service;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.neolix.watch.util.Constant;

import org.jetbrains.annotations.Nullable;

import static android.bluetooth.BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT;
import static com.neolix.watch.NeolixApplication.getInstance;
import static com.neolix.watch.bluetooth.BlueToothUtil.getCharacteristic;

public class SendDataService extends Service {
    private SendDataThread sendDataThread;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (sendDataThread == null) {
            sendDataThread = new SendDataThread();
            sendDataThread.start();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.d(Constant.BLUETOOTH_TAG, "send data thread stop");
        if (sendDataThread != null) {
            sendDataThread.cancel();
            sendDataThread = null;
        }

        super.onDestroy();
    }

    private class SendDataThread extends Thread {
        private boolean isExit;

        public void run() {
            Log.d(Constant.BLUETOOTH_TAG, getName() + "start send data thread");
            isExit = false;
            while (!isExit) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (getInstance().bluetoothLeService == null)
                    continue;

                BluetoothData data = getInstance().bluetoothLeService.getBluetoothData();
                if (data != null) {
                    BluetoothGattCharacteristic characteristic = getCharacteristic(data.getCommandType());
                    if (characteristic != null) {
                        characteristic.setWriteType(WRITE_TYPE_DEFAULT);
                        characteristic.setValue(data.getData());
                        getInstance().bluetoothLeService.writeCharacteristic(characteristic);
                        Log.d(Constant.BLUETOOTH_TAG, getName() + "write data type: " + data.getCommandType().toString());
                    } else
                        Log.d(Constant.BLUETOOTH_TAG, getName() + "write data error: " + data.getCommandType().toString() + " can not find Characteristic");
                }
            }
        }

        public void cancel() {
            isExit = true;
        }
    }
}
